package com.startrek.ch02;

import java.util.ArrayList;
import java.util.List;

public class DuplicatedValuesArray {

    public List<Integer> findDuplicatedValue(int[] a) {
        if (a == null || a.length == 0) {
            throw new IllegalArgumentException("Param should not be empty!");
        }

        List<Integer> results = new ArrayList<>();
        int n = a.length;

        for (int i = 0; i < n; i++) {
            boolean flag = true;
            while (i != a[i] && flag) {
                if (a[i] == a[a[i]]) {
                    results.add(a[i]);
                    flag = false;
                } else {
                    int temp = a[i]; // temp其实既是下标又是值
                    a[i] = a[temp];
                    a[temp] = temp;
                }
            }
        }

        return results;
    }
}
